package com.yulong.web.server.Impl;

import com.yulong.model.pojo.UmsMenu;
import com.yulong.web.dto.UmsMenuNode;
import com.yulong.web.mapper.UmsMenuMapper;
import com.yulong.web.server.UmsMenuServer;
import com.yulong.web.utils.ResponseMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UmsMenuServerImpl implements UmsMenuServer {

    @Autowired
    private UmsMenuMapper umsMenuMapper;

    @Override
    public ResponseMap create(UmsMenu umsMenu) {
        int i = umsMenuMapper.create(umsMenu);
        return ResponseMap.ok(i);
    }

    @Override
    public ResponseMap update(UmsMenu umsMenu) {
        int i = umsMenuMapper.update(umsMenu);
        return ResponseMap.ok(i);
    }

    @Override
    public ResponseMap delete(Long id) {
        int i = umsMenuMapper.delete(id);
        return ResponseMap.ok(i);
    }

    @Override
    public ResponseMap queryList(Integer level) {
        List<UmsMenu> umsMenus = umsMenuMapper.queryList(level);
        return ResponseMap.ok(umsMenus);
    }

    @Override
    public ResponseMap treeList() {
        List<UmsMenu> umsMenus = umsMenuMapper.selectAll();
        /**
         * 递归组装菜单树
         * 规则
         *        parent_id 为0的是 一级菜单
         *        parent_id 与 某个map 的id 相等  代表他有子级菜单
         */
        List<UmsMenuNode> result = umsMenus.stream().filter(i -> i.getParentId().equals(0L)).map(menu -> covertMenuNode(menu, umsMenus)).collect(Collectors.toList());
        return ResponseMap.ok(result) ;
    }


    /**
     * 将UmsMenu转化为UmsMenuNode并设置children属性
     */
    private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList){
        UmsMenuNode node = new UmsMenuNode();
        BeanUtils.copyProperties(menu,node);
        List<UmsMenuNode> children = menuList.stream().filter(subMenu -> subMenu.getParentId().equals(menu.getId())).map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node ;
    }
}
